package com.mission.game.components;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.mission.game.R;

public class PlayGPSHelper extends MapActivity {

	protected int _lat, _lon;
	protected GeoPoint _point;
	private MapView myMapView;
	private MapController myMapController;

	private LocationManager locMgr;
	private MyLocationListener locLstnr;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.gps_helper);
		myMapView = (MapView) findViewById(R.id.mapview);
		myMapController = myMapView.getController();
		myMapView.setBuiltInZoomControls(true);

		((Button) findViewById(R.id.gps_helper_button)).setText("Return");

		locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locLstnr = new MyLocationListener();
		locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
				locLstnr);

		if (!locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			showSettingsAlert();
		}

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			if (extras.containsKey("latitude")) {
				_lat = extras.getInt("latitude");
			} else {
				_lat = 0;
			}
			if (extras.containsKey("longitude")) {
				_lon = extras.getInt("longitude");
			} else {
				_lon = 0;
			}
		}
		_point = new GeoPoint(_lat, _lon);
		myMapController.animateTo(_point);
		Drawable marker = getResources().getDrawable(
				android.R.drawable.ic_menu_myplaces);
		marker.setBounds(0, 0, marker.getIntrinsicWidth(),
				marker.getIntrinsicHeight());
		myMapView.getOverlays().add(new InterestingLocations(marker, _point));
	}

	/**
	 * Function to show settings alert dialog
	 * */
	public void showSettingsAlert() {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(
				getBaseContext());

		// Setting Dialog Title
		alertDialog.setTitle("GPS settings");

		// Setting Dialog Message
		alertDialog
				.setMessage("GPS is not enabled. Do you want to go to settings menu?");

		// Setting Icon to Dialog
		// alertDialog.setIcon(R.drawable.delete);

		// On pressing Settings button
		alertDialog.setPositiveButton("Settings",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(
								Settings.ACTION_LOCATION_SOURCE_SETTINGS);
						getBaseContext().startActivity(intent);
					}
				});

		// on pressing cancel button
		alertDialog.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});

		// Showing Alert Message
		alertDialog.show();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public void backToTaskClicked(View v) {
		getIntent().putExtra("latitude", _lat).putExtra("longitude", _lon);
		setResult(RESULT_OK, getIntent());
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) { // Back key pressed
			getIntent().putExtra("latitude", _lat).putExtra("longitude", _lon);
			setResult(RESULT_OK, getIntent());
		}
		return super.onKeyDown(keyCode, event);
	}

	public class MyLocationListener implements LocationListener {
		@Override
		public void onLocationChanged(Location loc) {
			loc.getLatitude();
			loc.getLongitude();
			String coordinates[] = { "" + loc.getLatitude(),
					"" + loc.getLongitude() };
			PlayGPSHelper.this._lat = (int) (Double.parseDouble(coordinates[0]) * 1E6);
			PlayGPSHelper.this._lon = (int) (Double.parseDouble(coordinates[1]) * 1E6);

			GeoPoint p = new GeoPoint(PlayGPSHelper.this._lat,
					PlayGPSHelper.this._lon);

			myMapController.animateTo(p);
			myMapController.setZoom(7);
			myMapView.invalidate();

		}

		@Override
		public void onProviderDisabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Disabled",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onProviderEnabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Enabled",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {

		}

	}

	class InterestingLocations extends ItemizedOverlay<OverlayItem> {

		private List<OverlayItem> locations = new ArrayList<OverlayItem>();

		public InterestingLocations(Drawable defaultMarker, GeoPoint point) {
			super(boundCenterBottom(defaultMarker));
			// create locations of interest
			locations.add(new OverlayItem(point, "Task target", "Task target"));
			populate();
		}

		@Override
		protected OverlayItem createItem(int i) {
			return locations.get(i);
		}

		@Override
		public int size() {
			return locations.size();
		}

	}
}